/*
 * @Author: zxh
 * @Date: 2024-07-30 15:18:26
 * @LastEditors: zxh
 * @LastEditTime: 2024-07-31 09:14:12
 * @Description: 请填写简介
 */
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'
export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const cartList = ref<any[]>([])
    const updateNewList = async () => {
      const res = await findNewCartListAPI()
      cartList.value = res.result
    }
    const addCart = async (goods: any) => {
      if (isLogin.value) {
        const { skuId, count } = goods
        await insertCartAPI({ skuId, count })
        updateNewList()
      } else {
        // 添加购物车操作  已添加过 count+ 1 没有添加过直接push
        // 思路 通过匹配传递过来的商品对象中的skuId 能不能再cartList中找到，找到了就是添加过
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
          item.count++
        } else {
          cartList.value.push(goods)
        }
      }
    }
    const delCart = async (skuId: any) => {
      if (isLogin.value) {
        await delCartAPI([skuId])
        updateNewList()
      } else {
        //思路 1.找到要删除项的下标值 splice
        // 2.使用数组的过滤方法 filter
        const idx = cartList.value.findIndex((item) => skuId === item.skuId)
        cartList.value.splice(idx, 1)
      }
    }
    const clearCart = () => {
      cartList.value = []
    }
    //单选功能
    const singleCheck = (skuId: any, selected: boolean) => {
      const item = cartList.value.find((item) => item.skuId === skuId)
      item.selected = selected
    }
    // 全选功能
    const allCheck = (selected: boolean) => {
      //把cartList的每一项的selected都设置为当前的全选框状态
      cartList.value.forEach((item) => (item.selected = selected))
    }
    // 计算属性
    //1. 总的数量 所有项的count之和
    const allCount = computed(() => cartList.value.reduce((a, item) => a + item.count, 0))
    //2. 总价 所有项的count*price之和
    const allPrice = computed(() => cartList.value.reduce((a, item) => a + item.count * item.price, 0))
    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    // 已选择数量
    const selectedCount = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0)
    )
    // 已选择商品合计
    const selectedPrice = computed(() =>
      cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    )
    return {
      cartList,
      updateNewList,
      addCart,
      delCart,
      clearCart,
      singleCheck,
      allCheck,
      isAll,
      allCount,
      allPrice,
      selectedCount,
      selectedPrice
    }
  },
  {
    persist: true
  }
)
